package com.it.myh.semantic;

import com.it.myh.read.LocationAndTime;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class BaiduMapReverseGeocoding {
    public static String getSemantic(LocationAndTime locationAndTime) {
        Double latitude = locationAndTime.getLatitude();
        Double longitude = locationAndTime.getLongitude();
        // 提取语义信息
        String formatted_address = ""; // 地址全称
        String business = ""; // 商圈信息
        StringBuilder result = null;
        try {
            String location = latitude + "," + longitude; // 要查询的经纬度坐标
            String output = "json"; // 输出格式为JSON
            String ak = "Wevq2yw5vOu4odtf8N3Wogxal9x9YpI6"; // 百度地图API密钥
            String coordtype = "bd09ll"; // 坐标类型为百度地图坐标

            // 发送HTTP请求
            URL url = new URL("http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + ak + "&output=" + output + "&coordtype=" + coordtype + "&location=" + location);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.connect();

            // 解析返回结果
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            result = new StringBuilder();
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();


            JSONObject json = new JSONObject(result.toString());
            if (json.getInt("status") == 0) {
                JSONObject addressComponent = json.getJSONObject("result").getJSONObject("addressComponent");
                formatted_address = json.getJSONObject("result").getString("formatted_address");
                business = json.getJSONObject("result").getString("business");
            }

//            System.out.println("地址全称：" + formatted_address);
//            System.out.println("商圈信息：" + business);
//            System.out.println("result：" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return formatted_address;
    }
}
